package com.fjwt.gz.service.activity.coupon.send;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.coupon.SendCouponBo;
import com.fjwt.gz.coupon.gtpay.GtpayCouponSendService;
import com.fjwt.gz.db.bo.CouponResultBo;
import com.fjwt.gz.db.entity.FansEntity;
import com.fjwt.gz.db.entity.FansPayEntity;
import com.fjwt.gz.db.entity.PayAuthEntity;
import com.fjwt.gz.interfaces.ISendCouponService;
import com.fjwt.gz.service.impl.FansPayService;
import com.fjwt.gz.service.mapper.FansMapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class GtpaySendCouponService implements ISendCouponService {

    @Autowired
    private FansPayService fansPayService;
    @Autowired
    private FansMapper fansMapper;
    @Autowired
    private GtpayCouponSendService gtpayCouponSendService;


    private static final Logger gtPayLogger = LoggerFactory.getLogger("gtPay");

    @Override
    public CouponResultBo couponSend(PayAuthEntity authEntity, Long fansId, @NonNull String payConfig, Long couponIds) {
        String logPrefix = "【国通支付通道发券】";

        gtPayLogger.info("国通发券，支付通道方出资信息：{}，fansId：{}，,卡券payConfig：{}",
                JSON.toJSONString(authEntity), fansId, payConfig);
        SendCouponBo sendCouponBo = new SendCouponBo();
        // 获取openId
        String openId = getOpenId(authEntity, fansId, logPrefix);
        if (Objects.isNull(payConfig)) {
            throw new BizException("发券参数缺失！");
        }
        try {
            sendCouponBo.setOpenId(openId);
            sendCouponBo.setAppId("wx313cfd5a1d78e709");
            sendCouponBo.setStockId(payConfig);
            JSONObject jsonObject = gtpayCouponSendService.couponSend(sendCouponBo);
            String couponId = MapUtil.getStr(jsonObject, "coupon_id");

            CouponResultBo couponResultBo = new CouponResultBo();
            couponResultBo.setCouponId(couponId);// 通道方内部券id(tradeNo：平台订单号)
            couponResultBo.setCouponThirdId(couponId);
            gtPayLogger.info("{},发券成功返回信息：{}", logPrefix, JSONUtil.toJsonStr(couponResultBo));
            return couponResultBo;

        } catch (BizException e) {
            gtPayLogger.info("国通发券失败");
            throw e;
        } catch (Exception e) {
            gtPayLogger.info("国通发券失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取openId
     *
     * @param authEntity
     * @param fansId
     * @param logPrefix
     * @return
     */
    public String getOpenId(PayAuthEntity authEntity, Long fansId, String logPrefix) {
        String openId = "";
        if (0 == authEntity.getIsCommSubject()) {
            LambdaQueryWrapper<FansPayEntity> gw = FansPayEntity.gw();
            gw.eq(FansPayEntity::getIfCode, authEntity.getIfCode());
            gw.eq(FansPayEntity::getFansId, fansId);
            FansPayEntity fansOpen = fansPayService.getOne(gw);
            gtPayLogger.info("{}同主体查询返回信息：{}", logPrefix, JSONUtil.toJsonStr(fansOpen));
            if (Objects.isNull(fansOpen) || Objects.isNull(authEntity)) {
                throw new BizException("请用户先到活动详情页进行授权，然后再进行派发卡券！");
            }
            gtPayLogger.info("用户信息fansId:{},用户信息：{}", fansId, JSON.toJSONString(fansOpen));
            openId = fansOpen.getOpenId();
        } else {
            FansEntity fansEntity = fansMapper.selectById(fansId);
            gtPayLogger.info("{}异主体查询返回信息：{}", logPrefix, JSONUtil.toJsonStr(fansEntity));
            if (Objects.isNull(fansEntity) || Objects.isNull(authEntity)) {
                throw new BizException("发券参数缺失！");
            }
            gtPayLogger.info("用户信息fansId:{},用户信息：{}", fansId, JSON.toJSONString(fansEntity));
            openId = fansEntity.getPayOpenId();
        }
        return openId;
    }
}
